<template>
    <el-dialog v-model="state.show" :title="state.title" width="600px" destroy-on-close @closed="onClosed">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="APP ID" prop="appId">
                <el-input class="width440" v-model.trim="form.appId" show-word-limit placeholder="请输入APP ID" />
            </el-form-item>
            <el-form-item label="Secret" prop="appSecret">
                <el-input class="width440" v-model.trim="form.appSecret" placeholder="请输入Secret" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="state.show = false">取消</el-button>
            <el-button type="primary" @click="onConfirm(formRef)"> 确定 </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import request from '@/request';
import { ElMessage } from 'element-plus';
import { reactive, ref, inject } from 'vue';

const bus = inject('bus');
const state = reactive({
    show: false,
    title: '填写账号信息',
    type: 1 // 1: 绑定 2: 变更
});

const formRef = ref(null);
const form = reactive({
    applicationId: '',
    // APP ID
    appId: '',
    // Secret
    appSecret: ''
});
const rules = {
    appId: [{ required: true, message: '请输入APP ID', trigger: 'blur' }],
    appSecret: [{ required: true, message: '请输入Secret', trigger: 'blur' }]
};

const onClosed = () => {
    form.appId = '';
    form.appSecret = '';
};

const onConfirm = async formEl => {
    if (!formEl) return;
    await formEl.validate();
    let formData = {
        applicationId: form.applicationId,
        appId: form.appId,
        appSecret: form.appSecret
    };
    const api = state.type === 1 ? 'applicationBind' : 'applicationChangeBind';
    const message = state.type === 1 ? '绑定成功' : '变更成功';
    await request(api, formData);
    state.show = false;
    ElMessage.success(message);
    bus.emit('tabSwitch');
};
const getApplicationDetail = async () => {
    const res = await request('applicationDetail', { applicationId: form.applicationId });
    const data = res.data || {};
    form.appId = data.appId;
    form.appSecret = data.appSecret;
    state.show = true;
};

const onOpen = query => {
    form.applicationId = query.applicationId;
    state.type = query.state;
    if (query.state === 2) {
        getApplicationDetail();
    } else {
        state.show = true;
    }
};
defineExpose({
    onOpen
});
</script>
<style lang="scss" scoped>
:deep(.el-form-item__error) {
    margin-top: 4px;
}
</style>
